var seeds = {},
	id = 0,
	getUniqueId = function () {
	return id++;
};

$(function() {
	var doc = $(document),
		body = $('body'),
		sideContent = body.find('.side-content'),
		content = body.find('.content');
		previewContainer = body.find('.preview-container'),
		win = $(window), 
		preview = previewContainer.find('.preview');
	
	$.widget("MQM.sideBar", {

		_create: function () {
			var self = this,
				e = self.element;
				
			e.html(template("side-bar-tmpl"));
			self.top = e.find('.top');
			self.middle = e.find('.middle');
			self.bottom = e.find('.bottom');
			
			doc.on('click', '.frac-clicker', function (ev) {
				var box = $(this).prev();
				box.prop('disabled', false);
				box.select();
			});
			
			doc.on('blur', '.frac-box', function (ev) {
				ev.target.disabled = true;
			});
			
			window.setTimeout(function () {
				self.middle.css('height', sideContent.height() - self.top.height() - self.bottom.height() - 22 + 'px');
			}, 30);
			
			win.resize( function() {
				self.middle.css('height', sideContent.height() - self.top.height() - self.bottom.height() - 22 + 'px');
			});

			self.select = e.find('.type-select').on('change', function (e) {
				self.questionSelect();
			});
			
			self.add = e.find('.addUpdate').on('click', function () {
				self.questionAdd();
			});
			
			doc.on('seedremoved', function (ev, id) {
				if (id === self.currentSeed.id) {
					self.questionSelect();
				}
			});
			
			doc.on('seedselected', function (ev, seed) {
				self.currentSeed = seed;
				self.middle.html(template(self.currentSeed.type + '-sidebar-tmpl', self.currentSeed));
				self.middle.find('input, textarea').each(function (index,input) {
					$(input).val($(input).val().replace(/\\;/g,';'));
				});
				if (seed.type === "mc-bank") {
					var particles = self.middle.find('.container');
					if (seed.name.length > 0) {
						$.each(seed.name, function (index, element) {
							particles.append($('<div class="particle-widget"></div>').particle({seed: seed, index: index}));
						});
						particles.append($('<div class="particle-widget"></div>').particle());
					} else {
						particles.append($('<div class="particle-widget"></div>').particle());
						particles.append($('<div class="particle-widget"></div>').particle());
					}
				} else if (seed.type === "matching") {
					var particles = self.middle.find('.container');
					if (seed.atexts1.length > 0) {
						$.each(seed.atexts1, function (index, element) {
							particles.append($('<div class="matching-particle-widget"></div>').matchingparticle({seed: seed, index: index}));
						});
						particles.append($('<div class="matching-particle-widget"></div>').matchingparticle());
					} else {
						particles.append($('<div class="matching-particle-widget"></div>').matchingparticle());
						particles.append($('<div class="matching-particle-widget"></div>').matchingparticle());
					}
				} 
				if (seeds[seed.id]) {
					self.add.html('Update');
				} else {
					self.add.html('Add');
				}
				self.select.val(seed.type);
			});
			
			doc.on('blur', '.seed-data', function (ev) {
				var input = $(ev.target),
					expression = new RegExp(input.data('validation'));
					value = input.val();
					
				if (expression) {
					if (expression.test(value)) {
						input.removeClass('invalid');
					} else {
						input.addClass('invalid');
					}
				}
			});
			
			doc.on('questionselect', function () {
				self.questionSelect();
			});
			
			e.on('focus', '.mc-bank-particle:last .seed-data', function () {
				e.find('.container').append($('<div class="particle-widget"></div>').particle());
			});
			
			e.on('focus', '.matching-particle:last .seed-data', function () {
				e.find('.container').append($('<div class="matching-particle-widget"></div>').matchingparticle());
			});
			
			window.setTimeout(function () {
				self.questionSelect();
			}, 30);
			
		
		},
		
		questionSelect: function () {
			var self = this,
				e = self.element,
				seed;
			
			var qtype = self.select.find(":selected").data('value');
			if (qtype === 'mc-bank') {
			    seed =  MCBank();
			} else if (qtype === 'mc') {
				seed = MultiChoice();
			} else if (qtype === 'matching') {
				seed = Matching();
			} else if (qtype === 'truefalse') {
				seed = trueFalse();
			} else if (qtype === 'calculated') {
				seed = Calculated();
			}
			
			e.trigger('seedselected', seed);
		},
		
		questionAdd: function () {
			var e = this.element;
			
			e.find('.seed-data').each(function (index, element) {
				$(element).trigger('blur');
			});
			
			e.find('.particle-widget').each(function (index, element) {
				$(element).particle('validate');
			});
			
			e.find('.matching-particle-widget').each(function (index, element) {
				$(element).matchingparticle('validate');
			});
			
			
			//if (!e.find('.invalid').get(0)) {
				var self = this,
					e = self.element,
					obj = {};
					
				e.find('.seed-data-array').each(function (index, element) {
					element = $(element);
					var key = element.data('attribute'),
						data = element.val().replace(';','\;');
						
					if (typeof obj[key] === "undefined") {
						obj[key] = [];
					}
					
					obj[key].push(data);
				});
				
				e.find('.seed-data-single').each(function (index, element) {
					element = $(element);
					var key = element.data('attribute'),
						data = element.val().replace(/;/g,'\\;');
					obj[key] = data;
				});
				
				e.find('.seed-data-select').each(function (index, element) {
					element = $(element);
					var key = element.data('attribute'),
						data = element.find(':selected').data('value');
					
					obj[key] = data;
				});
				
				
				
				self.currentSeed.set(obj);
				
				var validation = self.currentSeed.validate();
				if (validation === "" && !e.find('.invalid').get(0)) {
					e.trigger('seedadded', self.currentSeed);
				} else {
					//alert(validation);
					//e.trigger('alert', validation);
					
					//get location from addButton Dimensions
					var addButton = body.find('.addUpdate');
					var addButtonRect = addButton[0].getBoundingClientRect();
					var addX = (addButtonRect.right + addButtonRect.left)/2;
					var addY = window.innerHeight - addButtonRect.top - 4;
					
					//remove any old error messages
					var oldbubble = body.find('.error-speech');
						oldbubble.remove();
						
						//add the alert bubble at the proper location
						var alertbubble = $('<div class="error-speech" style="left:' + 
											(-13 + addX) + 'px;bottom:' + (12 + addY) + 
											'px;">' + '<img src="GFX/error-x.png" align="top"> ' + validation + '</div>').appendTo(body);
						//fade out the alert bubble
						var wordcount = validation.split(" ").length;
						//console.log(wordcount);
						var commacount = 0;
						for(var i = 0; i < validation.length; i++) {
							if(validation[i] === ',') {
								commacount++;
							}
						}
						//console.log(commacount);
						window.setTimeout(function() {alertbubble.fadeOut(1000, function() {alertbubble.remove();});},(500*wordcount+250*commacount));
					
				}
				
			//} else {
				
			//}
		}
	});
	
	$.widget("MQM.particle", {
		options: {
			seed: null,
			index: null
		},
		_create: function () {
			var self = this,
				e = self.element;
				o = self.options;
				
			var seed = o.seed,
				index = o.index;
			
			if (seed) {
				var obj = {
					name: seed.name[index],
					question: seed.qtexts[index],
					answer:	seed.atexts[index],
					feedback: seed.feedback[index]
				};
			}
			
			e.html(template('mc-bank-particle-tmpl', obj));
			self.name = e.find('.name');
			self.question = e.find('.question');
			self.answer = e.find('.answer');
			self.feedback = e.find('.feedback');	
		},
		
		validate: function () {
			var self = this,
				e = self.element;
				if (!self._empty()) {
					if (self.name.val()) {
						self.name.removeClass('invalid');
					} else {
						self.name.addClass('invalid');
					}
					if (self.question.val()) {
						self.question.removeClass('invalid');
					} else {
						self.question.addClass('invalid');
					}
					if (self.answer.val()) {
						self.answer.removeClass('invalid');
					} else {
						self.answer.addClass('invalid');
					}
				}
				
			
		},
		
		_empty: function () {
			var self = this;
			return (!self.name.val() && !self.question.val() && !self.answer.val());
		}
	});
	
	$.widget("MQM.matchingparticle", {
		options: {
			seed: null,
			index: null
		},
		
		_create: function () {
			var self = this,
				e = self.element;
				o = self.options;
				
			var seed = o.seed,
				index = o.index;
			
			if (seed) {
				var obj = {
					p1: seed.atexts1[index],
					p2: seed.atexts2[index],
				};
			}
			
			e.html(template('matching-particle-tmpl', obj));
			self.p1 = e.find('.p1');
			self.p2 = e.find('.p2');	
		},
		
		validate: function () {
			var self = this,
				e = self.element;
				if (!self._empty()) {
					if (self.p1.val()) {
						self.p1.removeClass('invalid');
					} else {
						self.p1.addClass('invalid');
					}
					if (self.p2.val()) {
						self.p2.removeClass('invalid');
					} else {
						self.p2.addClass('invalid');
					}
				}
		},
		
		_empty: function () {
			var self = this;
			return (!self.p1.val() && !self.p2.val());
		}
	});
	
	var sidebar = sideContent.sideBar().resizable({
		handles:"e", 
		minWidth:"220",
		maxWidth:"800",
		helper:"ui-resizable-helper",
		stop: function(event, ui) {
			sideContent.css({
				width: sidebar.width() + 'px',
				height: '100%'
			});
			previewContainer.css('width', body.width() - sidebar.width()  - 1 + 'px');
		}
	});


});
